const ejs = require('ejs')
const path = require('path')
const fs = require('fs')
const fse = require('fs-extra')
const chalk = require('chalk')

const { SupportedLanguage, SupportedStyleSheets, SupportedFramework } = require('./consts')

module.exports = {
	apply: ({ framework, styleSheets, language }) => {
		const generateEslint = () => {
			const pkg = fse.readJSONSync(path.resolve(process.cwd(), './package.json'))
			const distName = pkg.type === 'module' ? 'eslint.config.cjs' : 'eslint.config.js'

			const eslintTemplate = path.resolve(__dirname, '../template/eslint.config.js')
			const eslintData = ejs.render(fs.readFileSync(eslintTemplate, 'utf-8'), {
				language,
				framework,
				supportedFramework: SupportedFramework,
				supportedLanguage: SupportedLanguage
			})

			const eslintFile = path.resolve(process.cwd(), './', distName)
			fse.ensureFileSync(eslintFile)
			fse.writeFileSync(eslintFile, eslintData, 'utf-8')
		}

		const generateStylelint = () => {
			// 生成 stylelint 配置文件
			const stylelintTemplate = path.resolve(__dirname, '../template/.stylelintrc.js')
			const stylelintData = ejs.render(fs.readFileSync(stylelintTemplate, 'utf-8'), {
				supportedStyleSheets: SupportedStyleSheets,
				styleSheets,
				vue: framework === SupportedFramework.vue2 || framework === SupportedFramework.vue3
			})

			const stylelintFile = path.resolve(process.cwd(), './.stylelintrc.js')
			fse.ensureFileSync(stylelintFile)
			fse.writeFileSync(stylelintFile, stylelintData, 'utf-8')
		}

		if (language !== SupportedLanguage.others) {
			console.log(chalk.blue('生成 ESLint 配置文件...'))
			try {
				generateEslint()
			} catch (e) {
				throw new Error('生成ESLint配置文件失败: ', e.message)
			}
		}

		if (styleSheets !== SupportedStyleSheets.others) {
			console.log(chalk.blue('生成 Stylelint 配置文件...'))
			try {
				generateStylelint()
			} catch (e) {
				throw new Error('生成Stylelint配置文件失败: ', e.message)
			}
		}
	}
}
